<script  lang="ts" setup>
import Inputter from "@/components/Inputter.vue";
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import type { FormRules } from "element-plus";
import Selector from "@/components/Selector.vue";
import { ElMessage } from 'element-plus';
import { onMounted } from "vue";
import instance from '@/utils/request';
import { useUserStore } from "@/stores/user";
import router from "@/router/router";

/*
    已废弃
*/

// 用户个人信息页面
onMounted(() => {
  init();
});

const user = useUserStore();

const dialogVisible = ref(false);
const dialogVisibleFirst = ref(false);
const isFirst = ref(false);

let customer_name = ref("");
let customer_sex = ref("");
let customer_id = ref("");
let customer_phone = ref("");

// 性别下拉框（表单）
const customer_sex_form_options = [
  { value: '男', label: '男' },
  { value: '女', label: '女' }
];

interface RuleForm {
  customer_name: string
  customer_sex: string
  customer_id: string
  customer_phone: string
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  customer_name: '',
  customer_sex: '',
  customer_id: '',
  customer_phone: ''
});

const rules = reactive<FormRules<RuleForm>>({
  customer_name: [
    { required: true, message: '姓名不能为空！', trigger: 'blur' }
  ],
  customer_sex: [
    { required: true, message: '性别不能为空！', trigger: 'blur' }
  ],
  customer_id: [
    { required: true, message: '身份证号不能为空！', trigger: 'blur' },
    { min: 18, max: 18, message: '请输入正确的身份证号！', trigger: 'blur' }
  ],
  customer_phone: [
    { required: true, message: '电话号码不能为空！', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入正确的电话号码！', trigger: 'blur' }
  ]
});

const submitForm =  (formEl: FormInstance | undefined) => {
  // 提交表单
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      dialogVisible.value = false;
      dialogVisibleFirst.value = false;
      if(isFirst.value) updateAll();
      else updatephone();
    }
  });
}

function open() {
  // 打开修改对话框
  if(customer_id.value === "无") isFirst.value = true;
  else isFirst.value = false;

  if(isFirst.value) dialogVisibleFirst.value = true;
  else dialogVisible.value = true;
}

function close() {
  // 关闭修改对话框
  dialogVisibleFirst.value = false;
  dialogVisible.value = false;
}

function init() {
  // 初始化
  instance.request({
    url: 'user/center/usermessage/init',
    method: 'POST',
    data: {
      user_id: user.user_id
    },
    headers: { "User-Id": user.user_id }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "初始化失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          customer_id.value = response.data.data[0].customer_id;
          customer_name.value = response.data.data[0].customer_name;
          customer_phone.value = response.data.data[0].customer_phone;
          customer_sex.value = response.data.data[0].customer_sex;
          if(response.data.data[0].customer_id === "无") {
            customer_sex.value = "无";
          }
        }
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "您的连接已被注销！",
            type: "error"
          });
          user.logout();
          router.push("/user/index");
          return;
        }
        ElMessage({
          message: "初始化失败！",
          type: "error"
        });
        setTimeout(() => {
          init();
        }, 2000 );
      });
}

function updateAll() {
  // 修改用户个人信息（首次）
  instance.request({
    url: 'user/center/usermessage/updateAll',
    method: 'POST',
    data: {
      user_id: user.user_id,
      customer_id: ruleForm.customer_id,
      customer_name: ruleForm.customer_name,
      customer_phone: ruleForm.customer_phone,
      customer_sex: ruleForm.customer_sex
    },
    headers: { "User-Id": user.user_id }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "修改失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          dialogVisibleFirst.value = false;
          ElMessage({
            message: "修改成功！",
            type: "success"
          });
        }
        init();
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "您的连接已被注销！",
            type: "error"
          });
          user.logout();
          router.push("/user/index");
          return;
        }
        ElMessage({
          message: "修改失败！",
          type: "error"
        });
      });
}

function updatephone() {
  //  修改用户个人信息的电话号码
  instance.request({
    url: 'user/center/usermessage/updatePhone',
    method: 'POST',
    data: {
      user_id: user.user_id,
      customer_phone: ruleForm.customer_phone
    },
    headers: { "User-Id": user.user_id }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "修改失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          dialogVisible.value = false;
          ElMessage({
            message: "修改成功！",
            type: "success"
          });
        }
        init();
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "您的连接已被注销！",
            type: "error"
          });
          user.logout();
          router.push("/user/index");
          return;
        }
        ElMessage({
          message: "修改失败！",
          type: "error"
        });
      });
}
</script>

<template>
  <el-dialog
      v-model="dialogVisibleFirst"
      :show-close="false"
      align-center
      width="25%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
    >
      <el-form-item label="姓名：" prop="customer_name">
        <inputter width="200" v-model="ruleForm.customer_name"/>
      </el-form-item>

      <el-form-item label="性别：" prop="customer_sex">
        <selector width="200" :options="customer_sex_form_options" v-model="ruleForm.customer_sex"/>
      </el-form-item>

      <el-form-item label="身份证号：" prop="customer_id">
        <inputter width="200" v-model="ruleForm.customer_id"/>
      </el-form-item>

      <el-form-item label="电话号码：" prop="customer_phone">
        <inputter width="200" v-model="ruleForm.customer_phone"/>
      </el-form-item>

      <div class="cancel-confirm">
        <el-button color="#568fc1" plain @click="close">
          <span>取消</span>
        </el-button>
        <el-button color="#568fc1" class="button-color"
                   @click="submitForm(ruleFormRef)">
          <span>修改</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog
      v-model="dialogVisible"
      :show-close="false"
      align-center
      width="25%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
    >
      <el-form-item label="电话号码：" prop="customer_phone">
        <inputter width="200" v-model="ruleForm.customer_phone"/>
      </el-form-item>

      <div class="cancel-confirm">
        <el-button color="#568fc1" plain @click="close">
          <span>取消</span>
        </el-button>
        <el-button color="#568fc1" class="button-color"
                   @click="submitForm(ruleFormRef)">
          <span>修改</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>

  <div class="message">
    <span class="message-text">姓名：</span>
    {{ customer_name }}<br><br>
    <span class="message-text">性别：</span>
    {{ customer_sex }}<br><br>
    <span class="message-text">身份证号：</span>
    {{ customer_id }}<br><br>
    <span class="message-text">电话号码：</span>
    {{ customer_phone }}<br><br>
    <el-button  color="#568fc1" class="button-width button-color" @click="open">
      <span>修改</span>
    </el-button>
  </div>
</template>

<style scoped>
.message {
  margin: 10vh;
  height: 50vh;
  /* border: 1px solid black; */
}
.message-text {
  display: inline-block;
  width: 12vh;
  text-align: right;
}
.button-width {
  margin-left: 5vh;
  width: 200px;
}
.button-color {
  --el-button-hover-bg-color: rgb(238, 244, 249) !important;
  --el-button-hover-text-color: #568fc1 !important;
  --el-button-text-color: white !important;
}
.cancel-confirm {
  padding-top: 1vh;
  text-align: center;
}
</style>